package py.com.alfa.escriba.gui.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.utils.command.AjaxResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.admin.PersonasControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.admin.ComparecientesDTO;
import py.com.alfa.escriba.gui.dto.admin.DomicilioDTO;
import py.com.alfa.escriba.gui.dto.admin.EscribanosDTO;
import py.com.alfa.escriba.gui.dto.admin.PersonaDTO;
import py.com.alfa.escriba.gui.dto.admin.PersonaInfoDTO;
import py.com.alfa.escriba.gui.dto.admin.PersonasdocumentosDTO;
import py.com.alfa.escriba.gui.dto.admin.PoderesDTO;
import py.com.alfa.escriba.gui.dto.admin.TabRefDTO;
import py.com.alfa.escriba.gui.dto.admin.TelefonoDTO;
import py.com.alfa.escriba.gui.rest.services.AdminService;
import py.com.alfa.escriba.gui.services.HelperService;
import py.com.alfa.escriba.gui.services.TabRef;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.alfa.escriba.gui.utils.DateUtils;
import py.com.alfa.escriba.gui.utils.ObjectUtils;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("personas")
@RequestMapping("/personas")
public class PersonasController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3807025844096914070L;
	private final static String PAGE_NAME = "pag:personas";
	private final static String CONTROLLER_OBJECT_NAME = "personas";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	@SpringBean private AdminService adminService;
	@SpringBean private HelperService helperService;
	
	@Autowired
	private WebApplicationContext wac;
	
	@Autowired
	private TemplateEngine templateEngine;
	@ControllerObject	
	private PersonasControllerObject personas;
	private Locale locale;
	private Long idTemp;
	
	
	public PersonasController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(PersonasController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}

	
	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public PersonasControllerObject getPersonas() {
		return this.personas;
	}

	public void setPersonas(PersonasControllerObject listas) {
		this.personas = listas;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.info("personas!");
		try {
			this.getPersonas().view().disableAll();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}
			loadObject();
			this.getPersonas().setEscribano(false);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.PERSONAS;
	}
	//TODO
	@RequestMapping(value = "/escribano", method = RequestMethod.GET)
	public String homePageEscribano(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.info("escribanos!");
		try {
			this.getPersonas().view().disableAll();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}
			loadObject();
			this.getPersonas().setEscribano(true);
			this.getPersonas().setEscribanoDTO(new EscribanosDTO());
			this.getPersonas().getPersona().setProfesionActividad("ESCRIBANO");
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.PERSONAS;
	}
	
	private void loadObject(){
		try {
			this.getPersonas().setEstadosCiviles(this.helperService.getTablaRef(TabRef.ESTADO_CIVIL));
			this.getPersonas().setGeneros(this.helperService.getTablaRef(TabRef.GENERO));
			this.getPersonas().setPaises(this.helperService.getPaises());
			this.getPersonas().setTiposPer(this.helperService.getTablaRef(TabRef.TIPO_PERSONA));
			this.getPersonas().setFiltros(null);
			this.getPersonas().setPersonas(null);
			this.getPersonas().view().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
	}

	@RequestMapping(value = "/agregarPersona", method = RequestMethod.POST)
	public @ResponseBody JsonResponse agregarPersona(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONAS) JsonResponse jResponse) {
		this.log.info("personas - Nuevo!");
		this.getPersonas().setPersona(new PersonaInfoDTO());
		this.getPersonas().getPersona().setActivo(true);
		idTemp=1L;
		try {
			this.getPersonas().getPersona().setPaisDTO(this.helperService.getPaisByCodigo("PRY"));
			this.getPersonas().getPersona().setTipoPersonaDTO(this.getPersonas().getTiposPer().get(0));
			this.getPersonas().setJuridica("JUR".equals(this.getPersonas().getPersona().getTipoPersonaDTO().getCodigo()));
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		this.getPersonas().view().disableAll().enable().persona();

		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/consultar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse consultar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("personas - consultar! {}");
		try {
			this.getPersonas().setPersonas(this.adminService.buscarPersonas(this.getPersonas().getFiltros()));
			this.getPersonas().view().disableAll().enable().lista();
			jResponse.setView(View.PERSONAS);
			} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/cancelar/{operacion}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		@PathVariable("operacion") String operacion) {
		this.log.info("personas - cancelar! {}", operacion);
		try {
			if ( operacion == null ) {
				return jResponse.error("Debe informar la operacion a cancelar");
			}
			if ( "DOMICILIO".equals(operacion)) {
				if ( this.getPersonas().getDomicilioOri() != null) {
					this.getPersonas().getPersona().getDomicilios().add(this.getPersonas().getDomicilioOri());
				}
				this.getPersonas().setDomicilioOri(null);
			    this.getPersonas().setDomicilio(null);
			    this.getPersonas().view().disableAll().enable().persona();
			} else	if ( "TELEFONO".equals(operacion)) {
				if ( this.getPersonas().getTelefonoOri() != null) {
					this.getPersonas().getPersona().getTelefonos().add(this.getPersonas().getTelefonoOri());
				}
				this.getPersonas().setTelefonoOri(null);
			    this.getPersonas().setTelefono(null);
			    this.getPersonas().view().disableAll().enable().persona();
			} else if ( "PERSONAS".equals(operacion)) {
			    this.getPersonas().setDomicilio(null);
			    this.getPersonas().setTelefono(null);
			    this.getPersonas().setPersona(null);
			    this.getPersonas().view().disableAll().enable().lista();
			    jResponse.setView(View.PERSONAS);
			}else if ( "DOCUMENTO".equals(operacion)) {
				if ( this.getPersonas().getDocumentoOri() != null) {
					this.getPersonas().getPersona().getDocumentos().add(this.getPersonas().getDocumentoOri());
				}
				this.getPersonas().setDocumentoOri(null);
			    this.getPersonas().setDocumento(null);
			    this.getPersonas().view().disableAll().enable().persona();
			}else if ( "LEGITIMACION".equals(operacion)) {
				if ( this.getPersonas().getComparecienteOri()!= null) {
					this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().add(this.getPersonas().getComparecienteOri());
				}
				this.getPersonas().setComparecienteOri(null);
			    this.getPersonas().setCompareciente(null);
			    this.getPersonas().view().disableAll().enable().persona();
			}
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/addDireccion", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addDireccion(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("personas - addDireccion!");
		try {
		    this.getPersonas().setDomicilio(null);
		    this.getPersonas().setDomicilioOri(null);
			this.getPersonas().setTipos(this.helperService.getTablaRef(TabRef.TIPO_DOMICILIO));
			this.getPersonas().setDepartamentos(this.helperService.getDepartamentos());
			
			this.getPersonas().setDistritos(null);
			if ( this.getPersonas().getDepartamentos() != null && !this.getPersonas().getDepartamentos().isEmpty()) {
			  this.getPersonas().setDistritos(this.helperService.getDistritos(this.getPersonas().getDepartamentos().get(0).getId()));	
			}
			
			this.getPersonas().view().enable().domicilio();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	@RequestMapping(value = "/departamentoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse departamentoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("INDICADOR DEPARTAMENTO EVENT! {}", this.getPersonas().getDomicilio().getDepartamento());
		try {
			this.getPersonas().setDistritos(null);
			this.getPersonas().setBarrios(null);
			if ( this.getPersonas().getDomicilio().getDepartamento() != null) {
				  Long id = this.getPersonas().getDomicilio().getDepartamento().getId();
				  this.getPersonas().getDomicilio().setDepartamento(this.helperService.getDepartamentoById(id));
				  this.getPersonas().setDistritos(this.helperService.getDistritos(id));				
		    }
			jResponse.setView(View.PERSONA_DIRECCION_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/distritoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse distritooEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("INDICADOR DISTRITO EVENT!");
		try {
			this.getPersonas().setBarrios(null);
			if ( this.getPersonas().getDomicilio().getDistrito() != null) {
				Long idDto = this.getPersonas().getDomicilio().getDepartamento().getId();
			  Long id = this.getPersonas().getDomicilio().getDistrito().getId();
			  this.getPersonas().getDomicilio().setDistrito(this.helperService.getDistritoById(idDto, id));				
			  this.getPersonas().setBarrios(this.helperService.getBarrios(this.getPersonas().getDomicilio().getDistrito().getId()));					
			}			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/guardarDomicilio", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarDomicilio(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("GUARDAR DOMICILIO!");
		try {
			// Verifico que se hayan cargado todos los valores
			Long id = null;
			Long idStr = null;
			Long idKey = null;
			
			if ( this.getPersonas().getDomicilio().getTipo() == null ) {
				return jResponse.error("Debe informar el tipo de domicilio");
			}
			if ( this.getPersonas().getDomicilio().getDepartamento() == null ) {
				return jResponse.error("Debe informar el departamento que pertenece el domicilio");
			}
			if ( this.getPersonas().getDomicilio().getDistrito() == null ) {
				return jResponse.error("Debe informar el distrito que pertenece el domicilio");
			}			
            
			id = this.getPersonas().getDomicilio().getTipo().getId();		    	
			for (DomicilioDTO obj : this.getPersonas().getPersona().getDomicilios()) {
				if ( obj.getTipo().getId().equals(id)) {
					return jResponse.error("Ya existe el tipo de domicilio que se quiere dar de alta");		
				}
			}
			this.getPersonas().getDomicilio().setTipo(this.helperService.getTablaRef(TabRef.TIPO_DOMICILIO, id));
			idStr = this.getPersonas().getDomicilio().getDepartamento().getId();
			this.getPersonas().getDomicilio().setDepartamento(this.helperService.getDepartamentoById(idStr));
			idKey = this.getPersonas().getDomicilio().getDistrito().getId();		    	
			this.getPersonas().getDomicilio().setDistrito(this.helperService.getDistritoById(idStr, idKey));
			DomicilioDTO domicilio = new DomicilioDTO();
			ObjectUtils.copyValues(this.getPersonas().getDomicilio(), domicilio);
			this.getPersonas().getPersona().getDomicilios().add(domicilio);
			this.getPersonas().setDomicilio(null);
			this.getPersonas().setDomicilioOri(null);
			this.getPersonas().view().disableAll().enable().persona();
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteDomicilio/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteDomicilio(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO DIRECCION! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DomicilioDTO obj = this.getPersonas().getPersona().getDomicilios().get(index);
			this.log.info("DOMICLIO: {}", obj);
			this.log.info("DOMICLIO ANTES SIZE LISTA: {}", this.getPersonas().getPersona().getDomicilios().size());
			if ( obj.getId() != null ) {
				this.getPersonas().getPersona().getEliminadosDomicilios().add(obj.getId());
			}
			this.getPersonas().getPersona().getDomicilios().remove(obj);
			this.log.info("DOMICLIO DESPUES SIZE LISTA: {}", this.getPersonas().getPersona().getDomicilios().size());
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarDomicilio/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarDomicilio(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR DIRECCION! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DomicilioDTO obj = this.getPersonas().getPersona().getDomicilios().get(index);
			this.log.info("DOMICLIO: {}", obj);
			this.getPersonas().setDomicilio(obj);
			this.getPersonas().setTipos(this.helperService.getTablaRef(TabRef.TIPO_DOMICILIO));
			this.getPersonas().setDepartamentos(this.helperService.getDepartamentos());
			this.getPersonas().setDistritos(this.helperService.getDistritos(obj.getDepartamento().getId()));								
			this.getPersonas().view().enable().domicilio();			
			this.getPersonas().setDomicilioOri(obj.clone());
			this.getPersonas().getPersona().getDomicilios().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	
	@RequestMapping(value = "/addTelefono", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addTelefono(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("personas - addTelefono!");
		try {
		    this.getPersonas().setTelefono(null);
		    this.getPersonas().setTelefonoOri(null);
			this.getPersonas().setTipos(this.helperService.getTablaRef(TabRef.TIPO_TELEFONO));
			this.getPersonas().view().enable().telefono();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/guardarTelefono", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarTelefono(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("GUARDAR TELEFONO!");
		try {
			// Verifico que se hayan cargado todos los valores
//			Long id = null;
			
			if ( this.getPersonas().getTelefono().getTipo() == null ) {
				return jResponse.error("Debe informar el tipo de Telefono");
			}
			if ( this.getPersonas().getTelefono().getNumero() == null ) {
				return jResponse.error("Debe informar el numero");
			}
            
//			id = this.getPersonas().getTelefono().getTipo().getId();		    	
			/*for (TelefonoDTO obj : this.getPersonas().getPersona().getTelefonos()) {
				if ( obj.getTipo().getId().equals(id)) {
					return jResponse.error("Ya existe el tipo de telefono que se quiere dar de alta");		
				}
			}*/
			
//			this.getPersonas().getTelefono().setTipo(this.helperService.getTablaRef(TabRef.TIPO_TELEFONO, id));
			TelefonoDTO telef = new TelefonoDTO();
			ObjectUtils.copyValues(this.getPersonas().getTelefono(), telef);
			this.getPersonas().getPersona().getTelefonos().add(telef);
			this.log.info("Telefono: {}", telef);
			this.getPersonas().setTelefono(null);
			this.getPersonas().setTelefonoOri(null);
			this.getPersonas().view().disableAll().enable().persona();
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteTelefono/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteTelefono(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO TELEFONO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			TelefonoDTO obj = this.getPersonas().getPersona().getTelefonos().get(index);
			this.log.info("Telefono: {}", obj);
			this.getPersonas().getPersona().getTelefonos().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarTelefono/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarTelefono(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR Telefono! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			TelefonoDTO obj = this.getPersonas().getPersona().getTelefonos().get(index);
			this.log.info("TELEFONO: {}", obj);
			this.getPersonas().setTelefono(obj);
			this.getPersonas().setTipos(this.helperService.getTablaRef(TabRef.TIPO_TELEFONO));
			this.getPersonas().view().enable().telefono();			
			this.getPersonas().setTelefonoOri(obj.clone());
			this.getPersonas().getPersona().getTelefonos().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/addDocumento", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addDocumento(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("personas - addDocumento!");
		try {
			
//			if(CollectionUtils.isEmpty(this.getPersonas().getTiposDoc()))
//		    	this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			
			PersonasdocumentosDTO doc = new PersonasdocumentosDTO();
			doc.setActivo(true);
			doc.setVencimiento(DateUtils.getCurrentDate());
			doc.setPaisDTO(this.helperService.getPaisByCodigo("PRY"));
			
			if(this.getPersonas().isJuridica()){
				doc.setTipoDocumento(this.helperService.getTablaRef(TabRef.TIPO_DOC, 9L));
				List<TabRefDTO> docList= new ArrayList<TabRefDTO>();
				docList.add(this.helperService.getTablaRef(TabRef.TIPO_DOC, 9L));
				this.getPersonas().setTiposDoc(docList);
				this.getPersonas().setRuc(true);
			}else{
				this.getPersonas().setRuc(false);
				this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			}
			
		    this.getPersonas().setDocumento(doc);
		    this.getPersonas().setDocumentoOri(doc);
		    
			this.getPersonas().view().enable().documento();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}

		return jResponse.success(request, response, wac, model, templateEngine);
	}	

	@RequestMapping(value = "/guardarDocumento", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarDocumento(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("GUARDAR DOCUMENTO!");
		try {
			// Verifico que se hayan cargado todos los valores
			Long id = null;
			
			if ( this.getPersonas().getDocumento().getIdtipodocumento() == null ) {
				return jResponse.error("Debe informar el tipo de documento");
			}
			if ( this.getPersonas().getDocumento().getNrodocumento() == null ) {
				return jResponse.error("Debe informar el nro de documento");
			}
			if (this.getPersonas().isRuc() && ObjectUtils.isEmpty(this.getPersonas().getDocumento().getDvdocumento()) ) {
				return jResponse.error("Debe informar el digito verificador");
			}
			if(this.getPersonas().getPersona().getDocumentos() == null){
				this.getPersonas().getPersona().setDocumentos(new ArrayList<PersonasdocumentosDTO>());
			}
            
			id = this.getPersonas().getDocumento().getIdtipodocumento();		    	
			for (PersonasdocumentosDTO obj : this.getPersonas().getPersona().getDocumentos()) {
				if (id.equals(obj.getIdtipodocumento())) {
					return jResponse.error("Ya existe el tipo de documento que se quiere dar de alta");		
				}
			}
			this.getPersonas().getDocumento().setTipoDocumento(this.helperService.getTablaRef(TabRef.TIPO_DOC, id));
			this.getPersonas().getDocumento().setPaisDTO(this.helperService.getPaisById(this.getPersonas().getDocumento().getPais()));
			this.getPersonas().getPersona().getDocumentos().add(this.getPersonas().getDocumento());
			this.getPersonas().setDocumento(null);
			this.getPersonas().setDocumentoOri(null);
			this.getPersonas().view().disableAll().enable().persona();
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	    
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteDocumento/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteDocumento(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO DOCUMENTO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			PersonasdocumentosDTO obj = this.getPersonas().getPersona().getDocumentos().get(index);
			this.log.info("DOCUMENTO: {}", obj);
			this.log.info("DOCUMENTO ANTES SIZE LISTA: {}", this.getPersonas().getPersona().getDocumentos().size());
			if ( obj.getId() != null ) {
				this.getPersonas().getPersona().getEliminadosDocumentos().add(obj.getId());
			}
			this.getPersonas().getPersona().getDocumentos().remove(obj);
			this.log.info("DOCUMENTO DESPUES SIZE LISTA: {}", this.getPersonas().getPersona().getDocumentos().size());
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarDocumento/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarDocumento(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR DOCUMENTO! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			PersonasdocumentosDTO obj = this.getPersonas().getPersona().getDocumentos().get(index);
			this.log.info("DOCUMENTO: {}", obj);
			
			if(ObjectUtils.isNotEmpty(obj.getPais()))
				obj.setPaisDTO(this.helperService.getPaisById(obj.getPais()));
			
			if(ObjectUtils.isNotEmpty(obj.getIdtipodocumento())){
				TabRefDTO tipodoc = this.helperService.getTablaRef(TabRef.TIPO_DOC, obj.getIdtipodocumento());
				obj.setTipoDocumento(tipodoc);
				this.getPersonas().setRuc("RUC".equals(tipodoc.getCodigo()));
			}
			
			if(CollectionUtils.isEmpty(this.getPersonas().getTiposDoc()))
				this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			
			this.getPersonas().setDocumento(obj);
			this.getPersonas().setDocumentoOri(obj.clone());
			this.getPersonas().view().enable().documento();
			this.getPersonas().getPersona().getDocumentos().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/tipoDocumentoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse tipoDocumentoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("INDICADOR TIPO DOCUMENTO EVENT! {}", this.getPersonas().getDocumento().getIdtipodocumento());
		try {
			TabRefDTO tipodoc = this.helperService.getTablaRef(TabRef.TIPO_DOC, this.getPersonas().getDocumento().getIdtipodocumento());
			this.getPersonas().getDocumento().setTipoDocumento(tipodoc);
			this.getPersonas().setRuc("RUC".equals(tipodoc.getCodigo()));
			jResponse.setView(View.PERSONA_DOCUMENTO_DIALOG);
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
	@RequestMapping(value = "/addLegitimacion", method = RequestMethod.POST)
	public @ResponseBody JsonResponse addLegitimacion(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("personas - addLegitimacion!");
		try {
		    this.getPersonas().setCompareciente(new ComparecientesDTO());
		    this.getPersonas().setComparecienteOri(new ComparecientesDTO());
		    this.getPersonas().setPoder(new PoderesDTO());
		    this.getPersonas().getCompareciente().setUsaPoder(false);
			this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			this.getPersonas().setRolesComp(this.helperService.getTablaRef(TabRef.ROLES_COMPARECIENTES));
			this.getPersonas().getCompareciente().setPaisDTO(this.helperService.getPaisByCodigo("PRY"));
			List<PoderesDTO> poderes=this.getPersonas().getPersona().getPersonaJuridica().getPoderes();
			if(poderes!=null){
				for(PoderesDTO pod : poderes){
					pod.setMarcar(false);
				}
			}
			this.getPersonas().view().enable().legitimacion();
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}	
	
	
	@RequestMapping(value = "/guardarLegitimacion", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarLegitimacion(Model model, HttpServletRequest request, HttpServletResponse response, 
	      @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("GUARDAR LEGITIMACION!");
		try {
			// Verifico que se hayan cargado todos los valores
			
//			if ( this.getPersonas().getCompareciente().getLegitimacion() == null ) {
//				return jResponse.error("Debe informar Legitimacion");
//			}
			if(this.getPersonas().getPersona().getPersonaJuridica().getComparecientes()==null){
				this.getPersonas().getPersona().getPersonaJuridica().setComparecientes(new ArrayList<ComparecientesDTO>());
			}
			if(this.getPersonas().getPersona().getPersonaJuridica().getPoderes()==null){
				this.getPersonas().getPersona().getPersonaJuridica().setPoderes(new ArrayList<PoderesDTO>());
			}
			
			if(this.getPersonas().getPoder()!=null && this.getPersonas().getPoder().getNombre()!=null){
				if(this.getPersonas().getPoder().getIdTemp()==null && this.getPersonas().getPoder().getId()==null){
				    this.getPersonas().getPoder().setIdTemp(idTemp);
				    idTemp++;
				    this.getPersonas().getPersona().getPersonaJuridica().getPoderes().add(this.getPersonas().getPoder());
				}
				if(this.getPersonas().getPoder().getIdTemp()!=null)
					this.getPersonas().getCompareciente().setIdTempPoder(this.getPersonas().getPoder().getIdTemp());
				if(this.getPersonas().getPoder().getId()!=null)
					this.getPersonas().getCompareciente().setIdPoder(this.getPersonas().getPoder().getId());
				this.getPersonas().getCompareciente().setPoder(this.getPersonas().getPoder());
			}
			Long idRol=this.getPersonas().getCompareciente().getRol().getId();
			this.getPersonas().getCompareciente().setRol(this.helperService.getTablaRef(TabRef.ROLES_COMPARECIENTES , idRol));
			Long idEstCiv=this.getPersonas().getCompareciente().getEstadoCivilDTO().getId();
			this.getPersonas().getCompareciente().setEstadoCivilDTO(this.helperService.getTablaRef(TabRef.ESTADO_CIVIL, idEstCiv));
			Long idTipDoc=this.getPersonas().getCompareciente().getTipoDocumento().getId();
			this.getPersonas().getCompareciente().setTipoDocumento(this.helperService.getTablaRef(TabRef.TIPO_DOC, idTipDoc));
//			ComparecientesDTO compareciente = new ComparecientesDTO();
//			ObjectUtils.copyValues(this.getPersonas().getCompareciente(), compareciente);	
			this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().add(this.getPersonas().getCompareciente());
			this.getPersonas().setCompareciente(null);
			this.getPersonas().setComparecienteOri(null);
			this.getPersonas().setPoder(null);
			this.getPersonas().view().disableAll().enable().persona();
			//jResponse.setView(View.PERSONA);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		this.log.info("GUARDAR LEGITIMACION!4 "+this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().size());
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }		

	@RequestMapping(value = "/deleteLegitimacion/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteLegitimacion(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO LEGITIMACION! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			ComparecientesDTO obj = this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().get(index);
			this.log.info("Legitimacion: {}", obj);
			if ( obj.getId() != null ) {
				this.getPersonas().getPersona().getEliminadosComparecientes().add(obj.getId());
			}
			this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editarLegitimacion/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarLegitimacion(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR LEGITIMACION! {}\n==============\n", ind);
		try {
			this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			this.getPersonas().setRolesComp(this.helperService.getTablaRef(TabRef.ROLES_COMPARECIENTES));
			Integer index = Integer.parseInt(ind);
			ComparecientesDTO obj = this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().get(index);
			this.log.info("Compareciente: {}", obj);
			List<PoderesDTO> poderes=this.getPersonas().getPersona().getPersonaJuridica().getPoderes();
			if(poderes!=null){
				for(PoderesDTO pod : poderes){
					pod.setMarcar(false);
				}
			}
			
			if(CollectionUtils.isEmpty(this.getPersonas().getTiposDoc()))
				this.getPersonas().setTiposDoc(this.helperService.getTablaRef(TabRef.TIPO_DOC));
			
			this.getPersonas().setCompareciente(obj);
			this.getPersonas().setComparecienteOri(obj.clone());
			if(obj.getPoder()!=null){
				this.getPersonas().setPoder(obj.getPoder());
				for(PoderesDTO pod : poderes){
					if(pod.equals(obj.getPoder())){
						pod.setMarcar(true);
						break;
					}
				}
			}
			this.getPersonas().view().enable().legitimacion();
			this.getPersonas().getPersona().getPersonaJuridica().getComparecientes().remove(obj);			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	@RequestMapping(value = "/checkPoder/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse checkPoder(Model model, HttpServletRequest request, HttpServletResponse response, 
		   @AjaxResponse(View.PERSONA) JsonResponse jResponse, 
	       @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult,
	       @PathVariable("index") String ind) {
		
		this.log.info("check Poder EVENT! {}", ind);
		try {
			Integer index = Integer.parseInt(ind);
			PersonaInfoDTO obj = this.getPersonas().getPersona();
			PoderesDTO dto = obj.getPersonaJuridica().getPoderes().get(index);
			if(dto!=null){
				Boolean ban= dto.getMarcar();
				if(this.getPersonas().getPersona().getPersonaJuridica().getPoderes()!=null){
					for(PoderesDTO pod : this.getPersonas().getPersona().getPersonaJuridica().getPoderes()){
						pod.setMarcar(new Boolean(false));
					}
					dto = obj.getPersonaJuridica().getPoderes().get(index);
					dto.setMarcar(ban);
				}
				if(ban){
					this.getPersonas().setPoder(dto);
				}else{
					this.getPersonas().setPoder(new PoderesDTO());
				}
			}
			jResponse.setView(View.PERSONA_LEGITIMACION_DIALOG);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
	@RequestMapping(value = "/usaPoderEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse usaPoderEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
		   @AjaxResponse(View.PERSONA) JsonResponse jResponse, 
	       @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("usa Poder EVENT! {}"+this.getPersonas().getCompareciente().getUsaPoder());
//		try {
//			Integer index = Integer.parseInt(ind);
//			PersonaInfoDTO obj = this.getPersonas().getPersona();
//			PoderesDTO dto = obj.getPersonaJuridica().getPoderes().get(index);
//			if(dto!=null){
//				this.getPersonas().setPoder(dto);
//			}
			jResponse.setView(View.PERSONA_LEGITIMACION_DIALOG);
//		} catch (Exception e) {
//			this.log.error(e.getMessage(), e);
//			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
//				return jResponse.error(e.getCause().getMessage());
//			}
//		}
//	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }

	@RequestMapping(value = "/guardarPersona", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("\n==============\nGUARDANDO PERSONA! \n==============\n");
		try {
			PersonaInfoDTO obj = this.getPersonas().getPersona();
			
			if ( CollectionUtils.isEmpty(obj.getDocumentos()) ) {
				return jResponse.error("Debe informar al menos un documento");
			}
			
			if ( obj.getId() == null ) {
				this.adminService.crearPersonaInfo(obj);
			} else {
			    this.adminService.actualizarPersonaInfo(obj);
			}
			this.getPersonas().setPersonas(this.adminService.buscarPersonas(this.getPersonas().getFiltros()));
			this.getPersonas().view().disableAll().enable().lista();
			jResponse.setView(View.PERSONAS);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarEscribano", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarEscribano(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		this.log.info("\n==============\nGUARDANDO Escribano! \n==============\n");
		try {
			EscribanosDTO obj = this.getPersonas().getEscribanoDTO();
			obj.setPersona(this.getPersonas().getPersona());
			if ( CollectionUtils.isEmpty(obj.getPersona().getDocumentos()) ) {
				return jResponse.error("Debe informar al menos un documento");
			}
			
			if ( obj.getId() == null ) {
				obj.setActivo(true);
				this.adminService.crearEscribano(obj);
			}
			
			this.getPersonas().setPersonas(this.adminService.buscarPersonas(this.getPersonas().getFiltros()));
			this.getPersonas().view().disableAll().enable().lista();
			jResponse.setView(View.PERSONAS);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}		
	
	
	@RequestMapping(value = "/editarPersona/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONAS) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR PERSONA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			PersonaDTO obj = this.getPersonas().getPersonas().get(index);
			this.log.info("PERSONA: {}", obj);
			PersonaInfoDTO persona = this.adminService.obtenerPersonaInfo(obj.getId());
			this.getPersonas().setPersona(persona);
			this.getPersonas().getPersona().setSexoDTO(this.helperService.getTablaRef(TabRef.GENERO, persona.getSexo()));
			this.getPersonas().getPersona().setTipoPersonaDTO(this.helperService.getTablaRef(TabRef.TIPO_PERSONA, persona.getTipoPersona()));
			this.getPersonas().setJuridica("JUR".equals(this.getPersonas().getPersona().getTipoPersonaDTO().getCodigo()));
			idTemp=1L;
			this.getPersonas().view().disableAll().enable().persona();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/eliminarPersona/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminarPersona(Model model,HttpServletRequest request, HttpServletResponse response, 
		         @AjaxResponse(View.PERSONAS) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== BORRAR PERSONA! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			PersonaDTO obj = this.getPersonas().getPersonas().get(index);
			this.log.info("PERSONA: {}", obj);
			this.adminService.eliminarPersonaInfo(obj.getId());
			this.getPersonas().setPersonas(this.adminService.buscarPersonas(this.getPersonas().getFiltros()));
			this.getPersonas().view().disableAll().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/escribanoEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse escribanoEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("INDICADOR ESCRIBANO EVENT! {}", this.getPersonas().getPersona().isEscribano());
		try {
			if(this.getPersonas().getPersona().isEscribano()){
				this.getPersonas().setJuridica(false);
				TabRefDTO per = this.helperService.getTablaRef(TabRef.TIPO_PERSONA, 18L);
				this.getPersonas().getPersona().setTipoPersonaDTO(per);
				this.getPersonas().setTiposPer(new ArrayList<TabRefDTO>());
				this.getPersonas().getTiposPer().add(per);
			}else{
				this.getPersonas().getPersona().setRegistroNro(null);
				this.getPersonas().setTiposPer(this.helperService.getTablaRef(TabRef.TIPO_PERSONA));
			}
			
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
	@RequestMapping(value = "/tipoPersonaEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse tipoPersonaEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.PERSONA) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) PersonasControllerObject personas, BindingResult bindingResult) {
		
		this.log.info("INDICADOR TIPO PERSONA EVENT! {}", this.getPersonas().getPersona().getTipoPersona());
		try {
			TabRefDTO per = this.helperService.getTablaRef(TabRef.TIPO_PERSONA, this.getPersonas().getPersona().getTipoPersona());
			this.getPersonas().getPersona().setTipoPersonaDTO(per);
			this.getPersonas().setJuridica("JUR".equals(per.getCodigo()));
			
			if(this.getPersonas().isJuridica()){
				this.getPersonas().getPersona().setApellidos(null);
				this.getPersonas().getPersona().setSexoDTO(null);
				this.getPersonas().getPersona().setEstadoCivilDTO(null);
			}
			
		} catch (IOException e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	 }
	
}	

